package com.masterclient.app.modules.income.dealer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.eoner.baselib.utils.status.StatusBarUtil;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.DoubleClickUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.modules.income.contract.DealerBankCardInsertContract;
import com.masterclient.app.modules.income.contract.DealerBankCardInsertPresenter;
import com.masterclient.app.modules.income.dealer.model.DealerBankCardBean;
import com.masterclient.app.modules.income.dealer.model.DealerBankCardMoreBean;
import com.masterclient.app.modules.income.model.ApplyWithdrawBean;
import com.masterclient.app.utils.CaptchaUtil;
import com.masterclient.app.utils.CommonUtil;
import com.masterclient.app.widget.TitlebarView;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//@Route(path = AroutePath.DEALER_BACK_CARD_INSERT_ACTIVITY)
public class DealerBankCardInsertActivity extends BaseActivity<DealerBankCardInsertPresenter> implements DealerBankCardInsertContract.View, TextWatcher {

    @BindView(R.id.title_view)
    TitlebarView title_view;

    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.card_id)
    TextView card_id;
    @BindView(R.id.bank_name)
    TextView bank_name;
    @BindView(R.id.bankcard_number)
    EditText bankcard_number;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.et_verify)
    EditText et_verify;
    @BindView(R.id.confirm_submit)
    TextView confirm_submit;
    @BindView(R.id.tv_get_yan)
    TextView tv_get_yan;
    @BindView(R.id.view_protocol)
    View viewProtocol;
    @BindView(R.id.iv_check)
    ImageView ivCheck;
    @BindView(R.id.tv_protocol_first)
    TextView tvProtocolFirst;
    @BindView(R.id.tv_protocol_middle)
    TextView tvProtocolMiddle;
    @BindView(R.id.tv_protocol_last)
    TextView tvProtocolLast;

    DealerBankCardBean bankCardData;
    String type = "1";
    CaptchaUtil captchaUtil;
    CountDownTimer timer;
    private boolean isSelected = false;
    private OptionsPickerView pvOptions;
    private String fromType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dealer_bank_card_bind);
        ButterKnife.bind(this);

        fromType = getBundleString("from_type");
        if (!TextUtils.isEmpty(fromType) && fromType.equals("applyWithdrawPage")){
            confirm_submit.setText("绑定并设为当前使用");
        }else {
            confirm_submit.setText("确认提交");
        }
        StatusBarUtil.setStatusBarColor(getActivity(), Color.parseColor("#FFFFFF"));
        bankCardData = (DealerBankCardBean) getIntent().getSerializableExtra("bankCardData");
        if (bankCardData != null) {
            type = "2";
        }

        viewProtocol.setVisibility(View.VISIBLE);
        captchaUtil = new CaptchaUtil(mContext, "绑定银行卡");
        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {
                if (!canCaptcha()) {
                    ToastUtil.showToast("请完善相关信息!");
                    return;
                }
                tv_get_yan.setClickable(false);
                mPresenter.getCaptcha(bank_id, bankcard_number.getText().toString().trim(), phone.getText().toString().trim(), type);
            }

            @Override
            public void onFailed() {
                tv_get_yan.setClickable(true);
            }
        });
        addListener();
        mPresenter.getBankCardMoreInfo();
    }

    private void addListener() {
        InputFilter inputFilter = (charSequence, i, i1, spanned, i2, i3) -> {
            if (charSequence.equals(" "))
                return "";
            return null;
        };

        name.addTextChangedListener(this);
        name.setFilters(new InputFilter[]{inputFilter});
        card_id.addTextChangedListener(this);
        card_id.setFilters(new InputFilter[]{inputFilter});
        card_id.setTransformationMethod(new ReplacementTransformationMethod() {
            @Override
            protected char[] getOriginal() {
                return new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
            }

            @Override
            protected char[] getReplacement() {
                return new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            }
        });
        bankcard_number.addTextChangedListener(this);
        phone.addTextChangedListener(this);
        et_verify.addTextChangedListener(this);
        title_view.setTitleSize(17);
        title_view.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
    }

    private boolean canCaptcha() {
        boolean nameFlag = !TextUtils.isEmpty(name.getText().toString().trim());
        boolean phoneFlag = !TextUtils.isEmpty(phone.getText().toString().trim());
        boolean idFlag = !TextUtils.isEmpty(card_id.getText().toString().trim());
        boolean bankCardFlag = !TextUtils.isEmpty(bankcard_number.getText().toString().trim());
        boolean bankFlag = !TextUtils.isEmpty(bank_id);
        return nameFlag && phoneFlag && idFlag && bankCardFlag && bankFlag;
    }

    private boolean canSubmit() {
        boolean nameFlag = !TextUtils.isEmpty(name.getText().toString().trim());
        boolean phoneFlag = !TextUtils.isEmpty(phone.getText().toString().trim());
        boolean idFlag = !TextUtils.isEmpty(card_id.getText().toString().trim());
        boolean bankCardFlag = !TextUtils.isEmpty(bankcard_number.getText().toString().trim());
        boolean bankFlag = !TextUtils.isEmpty(bank_id);
        boolean verifyFlag = !TextUtils.isEmpty(et_verify.getText().toString().trim());
        return nameFlag && phoneFlag && idFlag && bankCardFlag && bankFlag & verifyFlag;
    }

    public boolean isMobileNum(String phoneNum) {
        Pattern p = Pattern
                .compile("^((1[0-9]))\\d{9}$");
        return p.matcher(phoneNum).matches();
    }

    @OnClick({R.id.confirm_submit, R.id.bank_name, R.id.tv_get_yan, R.id.view_check,
            R.id.tv_protocol_first, R.id.tv_protocol_middle, R.id.tv_protocol_last})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirm_submit:
                String card_number = bankcard_number.getText().toString().trim();
                String bank_tel = phone.getText().toString();
                String captcha = et_verify.getText().toString().trim();

                if (!canSubmit()) {
                    return;
                }

                if (TextUtils.isEmpty(bank_id)) {
                    showToast("请选择所属银行");
                    return;
                }

                if (!isMobileNum(bank_tel)) {
                    showToast("手机号码格式不正确");
                    return;
                }

                if (!isSelected) {
                    showToast("请勾选协议");
                    return;
                }
                if (!DoubleClickUtil.isClick(1000)) {
                    return;
                }
                mPresenter.bindBankCard(bank_id, card_number, bank_tel, captcha, type);
                break;
            case R.id.bank_name:
                pvOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v1) -> {
                    //返回的分别是三个级别的选中位置
                    selected = banks.get(options1);
                    bank_id = selected.bankcardCertId;
                    bank_name.setText(selected.shortName);
                    bank_name.setTextColor(Color.parseColor("#000000"));
                    set_submit_clickable();
                }).setLayoutRes(R.layout.dialog_select_bank, (CustomListener) v12 -> {
                    final TextView tvSubmit = (TextView) v12.findViewById(R.id.tv_finish);
                    TextView ivCancel = (TextView) v12.findViewById(R.id.tv_cancel);
                    tvSubmit.setOnClickListener(v121 -> {
                        pvOptions.returnData();
                        pvOptions.dismiss();
                    });

                    ivCancel.setOnClickListener(v1212 -> pvOptions.dismiss());
                }).build();
                pvOptions.setPicker(banks);
                pvOptions.show();
                break;
            case R.id.tv_get_yan:
                if (!canCaptcha()) {
                    ToastUtil.showToast("请完善相关信息!");
                    return;
                }
                if (TextUtils.isEmpty(phone.getText().toString().trim())) {
                    showToast("输入银行预留的手机号");
                    return;
                }
                if (SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                    if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES) {
                        mPresenter.getCaptcha(bank_id, bankcard_number.getText().toString().trim(), phone.getText().toString().trim(), type);
                    } else {
                        captchaUtil.start();
                    }
                } else {
                    tv_get_yan.setClickable(false);
                    mPresenter.getCaptcha(bank_id, bankcard_number.getText().toString().trim(), phone.getText().toString().trim(), type);
                }
                break;
            case R.id.view_check:
                if (isSelected) {
                    isSelected = false;
                    ivCheck.setImageResource(R.mipmap.icon_dealer_protocol_check);
                } else {
                    isSelected = true;
                    ivCheck.setImageResource(R.mipmap.icon_dealer_protocol_checked);
                }
                break;
            case R.id.tv_protocol_first:
                CommonUtil.goAnyWhere(this, "https://auth.orangebank.com.cn/#/m/cDealOne?showNavBar=1", "", "", "", "");
                break;
            case R.id.tv_protocol_last:
            case R.id.tv_protocol_middle:
                CommonUtil.goAnyWhere(this, "https://my.orangebank.com.cn/orgLogin/hd/act//jianzb/jzbxym.html", "", "", "", "");
                break;
        }
    }

    List<DealerBankCardMoreBean.BankBean> banks = new ArrayList<>();
    DealerBankCardMoreBean.BankBean selected = null;
    String bank_id = "";

    @Override
    public void getBankCardMoreInfoSuccess(DealerBankCardMoreBean data) {
        if (data != null) {
            name.setText(data.realName);
            card_id.setText(data.idNo);
            if (data.bankList != null && data.bankList.size() > 0) {
                banks = data.bankList;
            }
        }
    }

    @Override
    public void getBankCardMoreInfoFail(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void bindSuccess(ApplyWithdrawBean data) {
        if (!TextUtils.isEmpty(fromType) && fromType.equals("applyWithdrawPage")) {
            showToast("更换成功");
            Intent intent = new Intent();
            intent.putExtra("bankName",bank_name.getText().toString().trim());
            intent.putExtra("bankCode", bankcard_number.getText().toString().trim());
            intent.putExtra("bankcardCertId", data.bankcardCertId);
            setResult(3, intent);
        } else {
            showToast("验证成功，银行卡已成功绑定");
            setResult(2);
        }
        finish();
    }

    @Override
    public void bindFailed(String msg) {
        showToast(msg);
    }

    @Override
    public void getCaptchaSuccess() {
        timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_get_yan.setTextColor(Color.parseColor("#999FAA"));
                String timeStr = millisUntilFinished / 1000 + "s";
                String temp = timeStr + "后重发";

                SpannableString spannableString = new SpannableString(temp);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#397BE6")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv_get_yan.setText(spannableString);
                tv_get_yan.setBackgroundResource(0);
            }

            @Override
            public void onFinish() {
                tv_get_yan.setClickable(true);
                String timeStr = "重新获取";
                tv_get_yan.setBackgroundResource(R.drawable.text_underline_397be6);

                SpannableString spannableString = new SpannableString(timeStr);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#397BE6")), 0, timeStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv_get_yan.setText(spannableString);
            }
        };
        timer.start();
    }

    @Override
    public void getCaptchaFailed(String msg) {
        tv_get_yan.setClickable(true);
        showToast(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        set_submit_clickable();
    }

    private void set_submit_clickable() {
        if (canSubmit()) {
            confirm_submit.setBackgroundResource(R.drawable.shape_round24_fc2a52);
            confirm_submit.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            confirm_submit.setBackgroundResource(R.drawable.shape_round24_f78296);
            confirm_submit.setTextColor(Color.parseColor("#FFE0E0"));
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    //点击空白区域，软键盘消失
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(getApplicationContext(), v.getWindowToken());
            }
            // 判断连续点击事件时间差
            if (isFastClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     */
    public static void hideSoftInput(Context context, IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token,
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     */
    public static boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            // 点击EditText的事件，忽略它。
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    private static final int MIN_DELAY_TIME = 300;  // 两次点击间隔不能少于1000ms
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

}
